/*
 * (c) 2014 Virtusa Corporation.
 * All Rights Reserved
 */
package ead.cs.service.impl;

import ead.cs.domain.ShipSchedule;
import ead.cs.repository.ShipScheduleRepository;
import ead.cs.service.ShipScheduleService;
import ead.cs.service.ShipService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class ShipScheduleServiceImpl implements ShipScheduleService {

    @Autowired
    private ShipScheduleRepository shipScheduleRepository;
    @Autowired
    private ShipService shipService;

    private static final Logger LOGGER = Logger.getLogger(ShipScheduleServiceImpl.class);

    @Override
    public List<ShipSchedule> getSchedule(String arrivalPort, String departurePort, Date startDate, Date endDate) {
        return shipScheduleRepository.findSchedules(arrivalPort, departurePort, startDate, endDate);
    }

    @Override
    public ShipSchedule getScheduleItem(String shipmentRef) {
        return shipScheduleRepository.findOne(shipmentRef);
    }

    @Override
    public void save(ShipSchedule shipSchedule) {
        LOGGER.debug(shipSchedule);
        if (shipSchedule == null || shipSchedule.getShip() == null || shipSchedule.getShip().getId() == null) {
            return;
        }
        shipSchedule.setShip(shipService.findOne(shipSchedule.getShip().getId()));
        shipScheduleRepository.save(shipSchedule);
    }

    @Override
    public Set<String> findDeparturePorts() {
        Set<String> portSet = new HashSet<String>();
        List<ShipSchedule> ports = shipScheduleRepository.findAll();
        for(ShipSchedule shipSchedule : ports){
            portSet.add(shipSchedule.getDeparturePort());
        }
        return portSet;
    }

    @Override
    public Set<String> findArrivalPorts() {
        Set<String> portSet = new HashSet<String>();
        List<ShipSchedule> ports = shipScheduleRepository.findAll();
        for(ShipSchedule shipSchedule : ports){
            portSet.add(shipSchedule.getArrivalPort());
        }
        return portSet;
    }
}
